package com.jhy.product.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.jhy.common.valid.AddGroup;
import com.jhy.common.valid.UpdateGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.jhy.product.entity.BrandEntity;
import com.jhy.product.service.BrandService;
import com.jhy.common.utils.PageUtils;
import com.jhy.common.utils.R;

import javax.validation.Valid;


/**
 * 品牌
 *
 * @author jhy
 * @email 2496085873@qq.com
 * @date 2021-05-09 11:02:17
 */
@RestController
@RequestMapping("product/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("product:brand:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = brandService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{brandId}")
    //@RequiresPermissions("product:brand:info")
    public R info(@PathVariable("brandId") Long brandId){
		BrandEntity brand = brandService.getById(brandId);

        return R.ok().put("brand", brand);
    }

    /**
     * 保存
     */
    //@Valid表明该实体中的字段需要进行校验 但是@Valid不能进行分组校验
    //使用@Validated可以指定分组，进行分组校验
    //给校验的Bean后，紧跟一个BindingResult，就可以获取到校验结果，拿到校验的结果，就可以自己进行封装
    @RequestMapping("/save")
    public R save(@Validated(AddGroup.class) @RequestBody BrandEntity brand/*, BindingResult result*/){

        //如果校验有误
        /*if(result.hasErrors()){
            //将错误封装到Map中，返回给前端
            Map<String,String> map = new HashMap<>();
            result.getFieldErrors().forEach((item)->{
                //获得发生错误的字段
                String field = item.getField();
                //获得发生错误的message
                String message = item.getDefaultMessage();
                map.put(field,message);
            });
            return R.error(404,"").put("data",map);
        }*/
		brandService.save(brand);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("product:brand:update")
    public R update(@Validated(UpdateGroup.class) @RequestBody BrandEntity brand){
		brandService.updateById(brand);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("product:brand:delete")
    public R delete(@RequestBody Long[] brandIds){
		brandService.removeByIds(Arrays.asList(brandIds));

        return R.ok();
    }

}
